﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using WucCloud.Application;
using WucCloud.Entity;
using WucCloud.Utility;

namespace WucCloud.WebApi.Areas.SystemManage.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [Area("SystemManage")]
    [Authorize(Policy = "Admin")]
    public class UserInfoController : ControllerBase
    {
        /// <summary>
        /// 自动映射
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 用户服务类
        /// </summary>
        private readonly UserInfoService _service;

        /// <summary>
        /// 用户角色服务类
        /// </summary>
        private readonly UserRoleService _userRoleService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="service"></param>
        /// <param name="userRoleService"></param>
        public UserInfoController(IMapper mapper,UserInfoService service, UserRoleService userRoleService)
        {
            _mapper = mapper;
            _service = service;
            _userRoleService = userRoleService;
        }

        #region 获取数据
        /// <summary>
        /// 通过Id查询
        /// </summary>
        /// <param name="keyId">主键Id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<UnifyResult>> FindById([Required] string keyId)
        {
            try
            {
                //通过Id查询用户数据
                var entity = await _service.FindById(keyId);

                //mapper映射
                var data = _mapper.Map<UserInfoDto>(entity);

                //判断是否获取到数据
                if (data == null)
                {
                    return new UnifyResult<dynamic>
                    {
                        StatusCode = ResultCode.NoneData,
                        Message = ResultCode.NoneData.Description(),
                        Data = null,
                        TotalCount = 0
                    };
                }
                //返回获取到的数据
                else
                {
                    return new UnifyResult<dynamic>
                    {
                        StatusCode = ResultCode.Success,
                        Message = ResultCode.Success.Description(),
                        Data = data,
                        TotalCount = 1
                    };
                }
            }
            catch (Exception ex)
            {
                return new UnifyResult()
                {
                    StatusCode = ResultCode.Error,
                    Message = ex.Message.ToString()
                };
            }
        }

        /// <summary>
        /// 自定义条件查询
        /// </summary>
        /// <param name="keyvalue">查询条件(编码/姓名)</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<UnifyResult>> GetList(string keyvalue)
        {
            try
            {
                //获取未锁定账户的用户数据
                var entity = await _service.GetList(keyvalue);

                //mapper映射
                var data = _mapper.Map<List<UserInfoDto>>(entity);

                //判断是否获取到数据
                if (data.Count == 0)
                {
                    return new UnifyResult<dynamic>
                    {
                        StatusCode = ResultCode.NoneData,
                        Message = ResultCode.NoneData.Description(),
                        Data = null,
                        TotalCount = 0
                    };
                }
                //返回获取到的数据
                else
                {
                    return new UnifyResult<dynamic>
                    {
                        StatusCode = ResultCode.Success,
                        Message = ResultCode.Success.Description(),
                        Data = data,
                        TotalCount = data.Count
                    };
                }
            }
            catch (Exception ex)
            {
                return new UnifyResult()
                {
                    StatusCode = ResultCode.Error,
                    Message = ex.Message.ToString()
                };
            }
        }

        /// <summary>
        /// 自定义条件分页查询
        /// </summary>
        /// <param name="keyvalue">查询条件（编码/姓名）</param>
        /// <param name="pageIndex">页数</param>
        /// <param name="pageSize">行数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<UnifyResult>> QueryPagedList(string keyvalue, [Required] int pageIndex, [Required] int pageSize)
        {
            //分页组件类
            PageModel page = new PageModel
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
            };

            try
            {
                //获取未锁定账户的用户分页数据
                var entity = await _service.QueryPagedList(keyvalue, page);

                //mapper映射
                var data = _mapper.Map<List<UserInfoDto>>(entity);

                //判断是否获取到数据
                if (data.Count == 0)
                {
                    return new UnifyResult<dynamic>
                    {
                        StatusCode = ResultCode.NoneData,
                        Message = ResultCode.NoneData.Description(),
                        Data = null,
                        TotalCount = 0
                    };
                }
                //返回获取到的数据
                else
                {
                    return new UnifyResult<dynamic>
                    {
                        StatusCode = ResultCode.Success,
                        Message = ResultCode.Success.Description(),
                        Data = data,
                        TotalCount = data.Count
                    };
                }
            }
            catch (Exception ex)
            {
                return new UnifyResult()
                {
                    StatusCode = ResultCode.Error,
                    Message = ex.Message.ToString()
                };
            }
        }

        /// <summary>
        /// 获取具有角色的用户列表
        /// </summary>
        /// <param name="roleId">角色主键Id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<UnifyResult>> GetRoleUsers([Required] string roleId)
        {
            try
            {
                var entity = await _userRoleService.GetRoleUsers(roleId);
                //判断是否获取到数据
                if (entity.Count == 0)
                {
                    return new UnifyResult<dynamic>
                    {
                        StatusCode = ResultCode.NoneData,
                        Message = ResultCode.NoneData.Description(),
                        Data = null,
                        TotalCount = 0
                    };
                }
                //返回获取到的数据
                else
                {
                    return new UnifyResult<dynamic>
                    {
                        StatusCode = ResultCode.Success,
                        Message = ResultCode.Success.Description(),
                        Data = entity,
                        TotalCount = entity.Count
                    };
                }
            }
            catch (Exception ex)
            {
                return new UnifyResult()
                {
                    StatusCode = ResultCode.Error,
                    Message = ex.Message.ToString()
                };
            }
            
        }
        #endregion

        #region 提交数据        
        /// <summary>
        /// 保存数据（新增/编辑）
        /// </summary>
        /// <param name="keyId">主键Id</param>
        /// <param name="entity">实体信息</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<UnifyResult>> SaveChange(string keyId, [FromForm] UserInfoEntity entity)
        {
            try
            {
                bool result = await _service.SaveChange(keyId, entity);
                if (!result)
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Failed,
                        Message = ResultCode.Failed.Description()
                    };
                }
                //操作成功
                else
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Success,
                        Message = ResultCode.Success.Description()
                    };
                }
            }
            catch (Exception ex)
            {
                return new UnifyResult()
                {
                    StatusCode = ResultCode.Error,
                    Message = ex.Message.ToString()
                };
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keyId">主键Id</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ActionResult<UnifyResult>> Deleteable([Required] string keyId)
        {
            try
            {
                bool result = await _service.Deleteable(keyId);
                //操作失败
                if (!result)
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Failed,
                        Message = ResultCode.Failed.Description()
                    };
                }
                //操作成功
                else
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Success,
                        Message = ResultCode.Success.Description()
                    };
                }
            }
            catch (Exception ex)
            {
                return new UnifyResult()
                {
                    StatusCode = ResultCode.Error,
                    Message = ex.Message.ToString()
                };
            }
            
        }

        /// <summary>
        /// 假删（逻辑删除）
        /// </summary>
        /// <param name="keyId"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ActionResult<UnifyResult>> SoftDeleteable([Required] string keyId)
        {
            try
            {
                bool result = await _service.SoftDeleteable(keyId);
                //操作失败
                if (!result)
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Failed,
                        Message = ResultCode.Failed.Description()
                    };
                }
                //操作成功
                else
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Success,
                        Message = ResultCode.Success.Description()
                    };
                }
            }
            catch (Exception ex)
            {
                return new UnifyResult()
                {
                    StatusCode = ResultCode.Error,
                    Message = ex.Message.ToString()
                };
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="keyIds">主键Id集合,以英文逗号分隔</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ActionResult<UnifyResult>> BatchDeleteable([Required] string[] keyIds)
        {
            try
            {
                bool result = await _service.BatchDeleteable(keyIds);
                //操作失败
                if (!result)
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Failed,
                        Message = ResultCode.Failed.Description()
                    };
                }
                //操作成功
                else
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Success,
                        Message = ResultCode.Success.Description()
                    };
                }
            }
            catch (Exception ex)
            {
                return new UnifyResult()
                {
                    StatusCode = ResultCode.Error,
                    Message = ex.Message.ToString()
                };
            }
        }

        /// <summary>
        /// 修改密码（新旧密码）
        /// </summary>
        /// <param name="keyId">主键Id</param>
        /// <param name="oldPwd">原密码</param>
        /// <param name="newPwd">新密码</param>
        /// <returns></returns>
        [HttpPatch]
        public async Task<ActionResult<UnifyResult>> UpdateablePwd([Required] string keyId, [Required] string oldPwd, [Required] string newPwd)
        {
            try
            {
                bool result = await _service.UpdateablePwd(keyId, oldPwd, newPwd);
                //操作失败
                if (!result)
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Failed,
                        Message = ResultCode.Failed.Description()
                    };
                }
                //操作成功
                else
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Success,
                        Message = ResultCode.Success.Description()
                    };
                }
            }
            catch (Exception ex)
            {
                return new UnifyResult()
                {
                    StatusCode = ResultCode.Error,
                    Message = ex.Message.ToString()
                };
            }
        }

        /// <summary>
        /// 锁定账户
        /// </summary>
        /// <param name="keyId">主键Id</param>
        /// <returns></returns>
        [HttpPatch]
        public async Task<ActionResult<UnifyResult>> LockAccount([Required] string keyId)
        {
            try
            {
                var result = await _service.LockAccount(keyId);
                //操作失败
                if (!result)
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Failed,
                        Message = ResultCode.Failed.Description()
                    };
                }
                //操作成功
                else
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Success,
                        Message = ResultCode.Success.Description()
                    };
                }
            }
            catch (Exception ex)
            {
                return new UnifyResult()
                {
                    StatusCode = ResultCode.Error,
                    Message = ex.Message.ToString()
                };
            }
            
        }

        /// <summary>
        /// 解锁账户
        /// </summary>
        /// <param name="keyId">主键Id</param>
        /// <returns></returns>
        [HttpPatch]
        public async Task<ActionResult<UnifyResult>> UnLockAccount([Required] string keyId)
        {
            try
            {
                var result = await _service.UnLockAccount(keyId);
                //操作失败
                if (!result)
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Failed,
                        Message = ResultCode.Failed.Description()
                    };
                }
                //操作成功
                else
                {
                    return new UnifyResult()
                    {
                        StatusCode = ResultCode.Success,
                        Message = ResultCode.Success.Description()
                    };
                }
            }
            catch (Exception ex)
            {
                return new UnifyResult()
                {
                    StatusCode = ResultCode.Error,
                    Message = ex.Message.ToString()
                };
            }
            
        }
        #endregion
    }
}
